<?php
// +----------------------------------------------------------------------
// | IPHP
// +----------------------------------------------------------------------
// | This is an open source and simple PHP FrameWork.
// +----------------------------------------------------------------------
// | Author: wuzhuo
// +----------------------------------------------------------------------

// 模型根类
namespace IPHP\Core;

class Model {
    protected $db;
    protected $tablename;   // 表名
    protected $primaryKey;  //主键
    protected $isMysql;     //　是否是mysql
    protected $tableFields; // 数据表的所有字段
    protected $pk;          //　自曾字段

    // 链式操作的值
    protected $order;
    protected $where;
    protected $fileds;
    protected $limit;
    protected $group;
    protected $having;
    protected $sql;
    protected $data;


    public function table($model_name) {
        $config = config('db');

        if(IS_SAE) {
            $sae_config = array(
                'host' => SAE_MYSQL_HOST_M,
                'port' => SAE_MYSQL_PORT,
                'user' => SAE_MYSQL_USER,
                'pwd' => SAE_MYSQL_PASS,
                'database' => SAE_MYSQL_DB,
            );
            $config = $config + $sae_config;
        }

        // 获取表名
        $tablename = $config['prefix'];
        for($i=0;$i<strlen($model_name);$i++){
            $char = substr($model_name,$i,1);
            $charord = ord($char);
            if($charord>64 && $charord<91){
                // 大写字母
                $tablename .= "_".strtolower($char);
            }
            if($charord>96 && $charord<123){
                // 小写字母
                $tablename .= $char;
            }           
        }

        $this->tablename = str_replace("__", "_", $tablename);

        $this->isMysql = false;
        switch (strtolower($config['type'])) {
            case 'mysql':
                $this->isMysql = true;
                if(!$config['port']) $config['port'] = 3306;
                $this->db = new \IPHP\DB\Mysql($config['host'], $config['port'], $config['user'], $config['pwd'], $config['database'], $config['prefix']);
                
                break;
            
            case 'mysqli':
                $this->isMysql = true;
                $this->db = new \IPHP\DB\Mysqli($config['host'], $config['port'], $config['user'], $config['pwd'], $config['database'], $config['prefix']);

                break;
        }

        // 获取数据表主键
        if($this->isMysql) {
            $f = $this->db->getallfields($this->tablename);
            $this->tableFields = $f['fields'];
            $this->pk = $f['pk'];
        }

        return $this->db;
    }


    /**
     * 插入数据
     * @return [type] [description]
     */
    public function insert($data="") {
        if($data) {
            $this->make($data);
        }
        return $this->_exec('insert');
    }

    /**
     * 删除数据
     * @return [type] [description]
     */
    public function delete($id="") {
        if($this->isMysql && is_numeric($id)) {
            $this->where = $this->pk." = '".$id."' ";
        }

        return $this->_exec("delete");
    }

    /**
     * 更新数据
     * @return [type] [description]
     */
    public function update() {
        if($data) {
            $this->make($data);
        }

        return $this->_exec("update");
    }

    /**
     * 获取表中所有数据
     * @return [type] [description]
     */
    public function fetchAll() {        
        $res = $this->_exec("select");
        return $res;
    } 

    /**
     * 获取表中一条数据
     * @return [type] [description]
     */
    public function fetch($id="") {
        if($this->isMysql && is_numeric($id)) {
            $this->where = $this->pk." = '".$id."' ";
        } 
        $res = $this->_exec("select");
        return $res[0];
    }

    /**
     * 获取满足条件的指定的字段
     * @return [type] [description]
     */
    public function field($field) {
        if($field) {
            $this->fields = $field;
        }
        $ret = $this->_exec("select");
        if(count($ret) == 1) {
            return $ret[0][$field];
        } elseif(!$ret) {
            return false;
        }
        return $ret;
    } 

    /**
     * 查询中使用where条件
     * @return [type] [description]
     */
    public function where($where) {
        $sql = $this->_parseCondition($where);
        $this->where = $sql;
        return $this;
    }

    /**
     * 指定要获取的字段名
     * @return [type] [description]
     */
    public function select($val = '*') {
        $this->fields = $val;
        return $this;
    }

    /**
     * 查询中使用orderby| groupby| having
     * @return [type] [description]
     */
    public function orderBy($val) {
        $this->order = $val;
        return $this;
    }

    public function groupBy($val) {
        $this->group = $val;
        return $this;
    }

    public function having($val) {
        $this->having = $val;
        return $this;
    }

    public function limit($val) {
        $this->limit = $val;
        return $this;
    }
    
    /**
     * 统计数据条数
     * @return [type] [description]
     */
    public function count($val='') {
        if($val) {
            $this->fields = $val;
        }
        $this->fields = " count(".$this->fields.")";
        return $this->_exec("select");
    }

    /**
     * 获取最大值
     * @return [type] [description]
     */
    public function max($val='') {
        if($val) {
            $this->fields = $val;
        }
        $this->fields = " max(".$this->fields.")";
        return $this->_exec("select");
    }

    /**
     * 获取最小值
     * @return [type] [description]
     */
    public function min($val='') {
        if($val) {
            $this->fields = $val;
        }
        $this->fields = " min(".$this->fields.")";
        return $this->_exec("select");
    }

    /**
     * 获取平均值
     * @return [type] [description]
     */
    public function avg($val='') {
        if($val) {
            $this->fields = $val;
        }
        $this->fields = " avg(".$this->fields.")";
        return $this->_exec("select");
    }

    /**
     * 获取和值
     * @return [type] [description]
     */
    public function sum($val='') {
        if($val) {
            $this->fields = $val;
        }
        $this->fields = " sum(".$this->fields.")";
        return $this->_exec("select");
    }

    /**
     * 字段递增
     * @return [type] [description]
     */
    public function inc($field, $i=1) {
        is_numeric($i) ? '' : $i = 1;
        $this->make(array($field=>$field." + ".abs($i)));
        $this->_exec('update');
    }

    /**
     * 字段递减
     * @return [type] [description]
     */
    public function dec($field, $i=1) {
        is_numeric($i) ? '' : $i = 1;
        $this->make(array($field=>$field." - ".abs($i)));        
        $this->_exec('update');
    }

    /**
     * 执行原始sql语句
     * 注意：传入的sql需要自行处理过滤
     * @return [type] [description]
     */
    public function query() {
        $args = func_get_args();
        $sql  = array_shift($args);

        if(count($args) > 0) {
            $funstr = '$sql = sprintf("'.$sql.'"';
            for($i = 0; $i < count($args); $i++) {
                $funstr .= ',$args['.$i.']';
            }
            $funstr.= ');';
            eval($funstr);
        }

        $this->sql = $sql;
        return $this->db->exec($this->sql);
    }

    /**
     * 创建数据对象
     * @return [type] [description]
     */
    public function make($data="") {
        $data = $data ? $data : $_POST;
        $obj = new \stdClass();
        if($data) {
            foreach ($data as $k => $v) {
                if(is_array($this->tableFields) && in_array($k,$this->tableFields)) {
                    $obj->$k = checkSql($v);
                }
            }
        }
        $this->data = $obj;
        return $obj;
    }

    /**
     * 解析sql条件
     * @param  [type] $c [description]
     * @return [type]    [description]
     */
    protected function _parseCondition($c) {
        return $this->db->parseCondition($c);
    }

    /**
     * 清除链式操作保存的数据
     * @return [type] [description]
     */
    protected function _clearCondition() {
        $this->order    = '';
        $this->where    = '';
        $this->fileds   = '';
        $this->limit    = '';
        $this->group    = '';
        $this->having   = '';
        $this->sql      = '';
        $this->data     = '';
    }

    /**
     * 执行sql
     * @return [type] [description]
     */
    protected function _exec($type="select") {
        $this->_createSql($type);
        $res = $this->db->exec($this->sql);
        $this->_clearCondition();
        return $res;
    }


    /**
     * 组装sql语句
     * @param  [type] $sql [description]
     * @return [type]      [description]
     */
    protected function _createSql($type = "select") {
        switch ($type) {
            case 'select':
                $this->sql = $this->db->createSelectSql($this->fields, $this->tablename, $this->where, $this->group, $this->having, $this->order, $this->limit);
                break;
            
            case 'delete':
                $this->sql = $this->db->createDeleteSql($this->tablename, $this->where, $this->limit);
                break;

            case 'insert':
                $this->sql = $this->db->createInserSQl($this->tablename, $this->data);
                break;

            case 'update':
                $this->sql = $this->db->createUpdateSQl($this->tablename, $this->where, $this->data);

                break;
        }
    }

    /**
     * 获取最近的一条sql
     * @return [type] [description]
     */
    public function info() {
        return $this->db->info();
    }

    public function __call($name,$arguments) {
        $this->db->$name();
    }

}